package com.topboya.linker.ui.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.android.flexbox.FlexboxLayout;
import com.topboya.linker.AppConst;
import com.topboya.linker.R;
import com.topboya.linker.diyview.CenteredEditText;
import com.topboya.linker.model.FollowUserDataManager;
import com.topboya.linker.model.OrgzitionManager;
import com.topboya.linker.model.levelitem.DepartmentGroupBo;
import com.topboya.linker.model.levelitem.FollowUserGroup;
import com.topboya.linker.model.response.CompanyUserListReponse;
import com.topboya.linker.model.response.FollowUserByOfficeResponse;
import com.topboya.linker.model.response.FollowUserLateResponse;
import com.topboya.linker.ui.adapter.FollowUserAdapter;
import com.topboya.linker.ui.adapter.RecycleViewDivider;
import com.topboya.linker.ui.base.activity.BaseActivity;
import com.topboya.linker.ui.presenter.FollowUserPrensenter;
import com.topboya.linker.ui.view.FollowUserView;
import com.topboya.linker.utils.AndroidUtils;
import com.topboya.linker.utils.LogUtils;
import com.topboya.linker.utils.UIUtils;

import java.util.ArrayList;
import java.util.List;

public class FollowUserActivity extends BaseActivity<FollowUserView,FollowUserPrensenter> implements FollowUserView  {

    private static final String TAG = "FollowUserActivity:";
    private Toolbar toolbar;
    private TextView toolbar_title;
    private RecyclerView recycle_org;
    private CenteredEditText et_search_devices;
    private List<FollowUserGroup> followUserGroups;
    private FollowUserAdapter followUserAdapter;
    private LinearLayout ll_department;
    private LinearLayout ll_organization;
    private Button btn_selected;
    private Button btn_select;
    private  FollowUserDataManager followUserDataManager;
    private RelativeLayout rl_follow_head;
    private FlexboxLayout flex_followuser_contents;
    private List<FollowUserGroup> followUserGroupsearch;
//    用来保存被选中的随访人
    private ArrayList<FollowUserGroup> selectfollowuser;
//    用来保存是否跳转到搜索页面，如果是的就
    private boolean isToSearch = false;
   private Handler mHandler  = new Handler(){
       @Override
       public void handleMessage(Message msg) {
           super.handleMessage(msg);

           if (isToSearch){
             isToSearch = false;
//               跳转到搜索页面
             OrgzitionManager.getIntanse().setfollowUserGroupsData(followUserGroupsearch);
             Intent intent = new Intent(FollowUserActivity.this,SearchFollowUserActivity.class);
             intent.putExtra("selectfollowuser",selectfollowuser);
             startActivityForResult(intent,1001);

           }else {
               for (FollowUserGroup followUserGroup:followUserGroups){
                   ArrayList<FollowUserGroup> selectfollowUserGroup = new ArrayList();
                   selectfollowUserGroup.clear();
                   getALLOfChildDeptsSize(followUserGroup.getSubGroupBosCd(), selectfollowUserGroup);
                   followUserGroup.setTotalNum(String.valueOf(selectfollowUserGroup.size()));
               }
               for (FollowUserGroup followUserGroup:followUserGroups){

                   ArrayList<FollowUserGroup> selectfollowuser = new ArrayList();
                   selectfollowuser.clear();
                   getAllSelectDepts(followUserGroup.getSubGroupBosCd(),selectfollowuser);
                   followUserGroup.setSelectNum(String.valueOf(selectfollowuser.size()));
               }
               followUserAdapter.setNewData(followUserGroups);
           }

           hideWaitingDialog();
       }


   };


    @Override
    protected int getLayoutId() {

        return R.layout.xactivity_follow_user;
    }

    @Override
    protected void initView() {

        toolbar = findViewById(R.id.toolbar);
        toolbar_title = findViewById(R.id.toolbar_title);
        recycle_org = findViewById(R.id.recycle_org);
        ll_department = findViewById(R.id.ll_department);
        ll_organization = findViewById(R.id.ll_organization);
        btn_selected = findViewById(R.id.btn_selected);
        rl_follow_head = findViewById(R.id.rl_follow_head);
        flex_followuser_contents = findViewById(R.id.flex_followuser_contents);
        btn_select = findViewById(R.id.btn_select);
        et_search_devices = findViewById(R.id.et_search_devices);
        et_search_devices.setInputType(InputType.TYPE_NULL);
        followUserDataManager = new FollowUserDataManager();
        initRycyclview();
        flex_followuser_contents.addView(createNewFlexItemTextView("Linker"));

    }

    private TextView createNewFlexItemTextView( String textname) {

        TextView textView = new TextView(this);
        textView.setGravity(Gravity.CENTER);
        textView.setText(textname);
        textView.setTextSize(16);
        textView.setTextColor(getResources().getColor(R.color.home_bottom_text_checked));
        if (flex_followuser_contents.getChildCount() >= 1){

            Drawable drawable = getResources().getDrawable(R.drawable.rightarrow);
            drawable.setBounds(0,0, drawable.getMinimumWidth(), drawable.getMinimumHeight());
            textView.setCompoundDrawables(drawable,null,null,null);
            textView.setCompoundDrawablePadding(AndroidUtils.dpToPixel(this,10));
        }
        textView.setOnClickListener(view -> {

            int index = flex_followuser_contents.indexOfChild(view);
            int totalcount = flex_followuser_contents.getChildCount();
            for (int i=totalcount;index !=0 && index !=1 && i>index;i--){

                followUserGroups =followUserGroups.get(0).getDeptGroupBosPs();
                int totalcountremvoe = flex_followuser_contents.getChildCount();
                flex_followuser_contents.removeViewAt(totalcountremvoe-1);
            }
            followUserAdapter.setNewData(followUserGroups);

        });
//        int padding = AndroidUtils.dpToPixel(this, 4);
//        int paddingLeftAndRight = AndroidUtils.dpToPixel(this, 8);
//        ViewCompat.setPaddingRelative(textView, paddingLeftAndRight, padding, paddingLeftAndRight, padding);
        FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT,
                ViewGroup.LayoutParams.WRAP_CONTENT);
        int margin = AndroidUtils.dpToPixel(this, 20);
        int marginTop = AndroidUtils.dpToPixel(this, 10);
        layoutParams.setMargins(marginTop, marginTop, 0, marginTop);
        textView.setLayoutParams(layoutParams);
        return textView;
    }
    private void initRycyclview() {

        RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
        recycle_org.setLayoutManager(layoutManager);
        recycle_org.addItemDecoration(new RecycleViewDivider(this, LinearLayoutManager.HORIZONTAL, 2, 0xBFC0C2));
        followUserAdapter = new FollowUserAdapter(followUserGroups);
        recycle_org.setAdapter(followUserAdapter);

    }

    @Override
    protected void initData() {
         isToSearch =false;
        followUserGroupsearch = new ArrayList<>();
//        保存添加的随访人
        selectfollowuser = new ArrayList();
        ArrayList<FollowUserGroup> selectfollowuser = (ArrayList<FollowUserGroup>) getIntent().getSerializableExtra("selectfollowuser");
        if (null !=selectfollowuser){

            this.selectfollowuser.addAll(selectfollowuser);
        }
        btn_selected.setText("已选择："+ this.selectfollowuser.size());

        toolbar_title.setText("选择随访人");
        mPresenter.getFollowUser("1");

    }

    @Override
    protected void initListener() {

        toolbar.setNavigationOnClickListener(v -> { back();});
        et_search_devices.setOnClickListener(v -> {

            isToSearch =true;
            mPresenter.getCompanyUserList();

        });
        ll_department.setOnClickListener(v -> {

            rl_follow_head.setVisibility(View.GONE);
            flex_followuser_contents.setVisibility(View.VISIBLE);
            mPresenter.getFollowUserByOffice(AppConst.OFFICEID);
            flex_followuser_contents.addView(createNewFlexItemTextView("我的部门"));

        });

        ll_organization.setOnClickListener(v -> {

            rl_follow_head.setVisibility(View.GONE);
            flex_followuser_contents.setVisibility(View.VISIBLE);
            flex_followuser_contents.addView(createNewFlexItemTextView("组织架构"));

            mPresenter.getCompanyUserList();

        });

        followUserAdapter.setOnItemClickListener((adapter, view, position) -> {

            if (null==followUserGroups.get(position).getSubGroupBosCd() ||0== followUserGroups.get(position).getSubGroupBosCd().size()){

//                UIUtils.showToast("到底了");

            }else {

                if (followUserGroups.get(position).isSub()){

                    flex_followuser_contents.addView(createNewFlexItemTextView(followUserGroups.get(position).getName()));

                }
                followUserGroups =followUserGroups.get(position).getSubGroupBosCd();

                for (FollowUserGroup followUserGroup:followUserGroups){
                    ArrayList<FollowUserGroup> selectfollowUserGroup = new ArrayList();
                    selectfollowUserGroup.clear();
                    getALLOfChildDeptsSize(followUserGroup.getSubGroupBosCd(),selectfollowUserGroup);
                    followUserGroup.setTotalNum(String.valueOf(selectfollowUserGroup.size()));
                }

                for (FollowUserGroup followUserGroup:followUserGroups){

                    ArrayList<FollowUserGroup> selectfollowuser = new ArrayList();
                    selectfollowuser.clear();
                    getAllSelectDepts(followUserGroup.getSubGroupBosCd(),selectfollowuser);
                    followUserGroup.setSelectNum(String.valueOf(selectfollowuser.size()));
                }

                followUserAdapter.setNewData(followUserGroups);
            }
        });


        followUserAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            switch (view.getId()){

                case R.id.ck_select:

                    boolean ischecked = followUserGroups.get(position).isCheked();
                    LogUtils.v(TAG + "ischecked:"+ischecked);

                    if (selectfollowuser.size() < 4 && !ischecked){

                        followUserGroups.get(position).setCheked(!ischecked);

                    }else {
                        if (!ischecked){

                            followUserGroups.get(position).setCheked(ischecked);
                            UIUtils.showToast("随访人数最多添加4人");

                        }else {
                            followUserGroups.get(position).setCheked(!ischecked);
                        }
                    }
                    followUserAdapter.setNewData(followUserGroups);
                    if (!ischecked){

                        if (selectfollowuser.size()==0){

                            selectfollowuser.add(followUserGroups.get(position));
                        }

                        for (int i=0;i <selectfollowuser.size() && selectfollowuser.size()<4;i++){

                            if (!selectfollowuser.get(i).getName().equals(followUserGroups.get(position).getName())){
                                if (i==selectfollowuser.size()-1){
                                    selectfollowuser.add(followUserGroups.get(position));
                                }
                            }
                        }
                    }else {

                        for (int i=0;i <selectfollowuser.size();i++){

                            if (selectfollowuser.get(i).getName().equals(followUserGroups.get(position).getName())){

                                 selectfollowuser.remove(i);

                            }
                        }
                    }
                    btn_selected.setText("已选择："+selectfollowuser.size());
                    break;
            }
        });
        btn_select.setOnClickListener(v -> {
//              返回选中随访人的信息
            //数据是使用Intent返回
            Intent intent = new Intent();
            //把返回数据存入Intent
            intent.putExtra("selectfollowuser", selectfollowuser);
//        intent.putExtra("fileLists", fileListss);
            //设置返回数据
            setResult(1003, intent);
            //关闭Activity
            finish();

        });

    }

    public  void getAllSelectDepts(List<FollowUserGroup> followUserGroupsBo,List<FollowUserGroup> selectdepts){

        if (null !=followUserGroupsBo){

            for (FollowUserGroup followUserGroup: followUserGroupsBo) {

                if (!followUserGroup.isSub() && followUserGroup.isCheked()){

                    selectdepts.add(followUserGroup);
                    LogUtils.v(TAG + "NAME:"+followUserGroup.getName());
                }
                getAllSelectDepts(followUserGroup.getSubGroupBosCd(),selectdepts);
            }
        }
    }



    @Override
    protected FollowUserPrensenter createPresenter() {

        return new FollowUserPrensenter(this);
    }

    @Override
    public void getFollowUser(List<FollowUserLateResponse.LateUser> lateUserlist) {

        LogUtils.v(TAG + "lateUserlist:"+lateUserlist.toString());

         followUserGroups = followUserDataManager.getlateFollowUserlist(lateUserlist,selectfollowuser);
         followUserAdapter.setNewData(followUserGroups);

    }

    @Override
    public void getFollowUserByOffice(List<FollowUserByOfficeResponse.SameDepartList> sameDepartLists) {

        LogUtils.v(TAG + "sameDepartLists:"+sameDepartLists.toString());

        followUserGroups = followUserDataManager.getSameFollowUserlist(sameDepartLists,selectfollowuser);
        followUserAdapter.setNewData(followUserGroups);


    }

    @Override
    public void getCompanyUserList(List<CompanyUserListReponse.Data> comuserlists) {
        showWaitingDialog("请稍后");
       new Thread(){
           @Override
           public void run() {

               if (isToSearch){

                   followUserGroupsearch.clear();
                   followUserGroupsearch.addAll(followUserDataManager.getCompanyUserList(comuserlists,selectfollowuser));

               }else {

                   followUserGroups = followUserDataManager.getCompanyUserList(comuserlists,selectfollowuser);

               }
               mHandler.sendEmptyMessage(1);
           }
         }.start();

    }
    //    得到当前节点所有子节点为部门成员的个数
    public void  getALLOfChildDeptsSize(List<FollowUserGroup> followUserGroups, List<FollowUserGroup> selectdepts) {

        if (null !=followUserGroups){

        for (FollowUserGroup followUserGroup : followUserGroups) {

            if (!followUserGroup.isSub()) {

                selectdepts.add(followUserGroup);
            }
            getALLOfChildDeptsSize(followUserGroup.getSubGroupBosCd(), selectdepts);
        }
      }
    }
    @Override
    public void onBackPressed() {

          back();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // 是否触发按键为back键
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            onBackPressed();
            return true;
        } else { // 如果不是back键正常响应
            return super.onKeyDown(keyCode, event);
        }
    }

    private void back() {

        if (null==followUserGroups.get(0).getDeptGroupBosPs()||0== followUserGroups.get(0).getDeptGroupBosPs().size()){
//            UIUtils.showToast("到头了");
//            到头了，并且页面还是我的部门或者组织架构下面，则返回到我最近、
            if (View.GONE ==rl_follow_head.getVisibility()){

                rl_follow_head.setVisibility(View.VISIBLE);
                flex_followuser_contents.removeViewAt(flex_followuser_contents.getChildCount() -1);
                flex_followuser_contents.setVisibility(View.GONE);
                mPresenter.getFollowUser("1");

            }else {

                super.onBackPressed();
            }
        }else {

            followUserGroups =followUserGroups.get(0).getDeptGroupBosPs();
            for (FollowUserGroup followUserGroup:followUserGroups){

                ArrayList<FollowUserGroup> selectfollowuser = new ArrayList();
                selectfollowuser.clear();
                getAllSelectDepts(followUserGroup.getSubGroupBosCd(),selectfollowuser);
                followUserGroup.setSelectNum(String.valueOf(selectfollowuser.size()));
            }
            followUserAdapter.setNewData(followUserGroups);
            flex_followuser_contents.removeViewAt(flex_followuser_contents.getChildCount() -1);

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        selectfollowuser = (ArrayList<FollowUserGroup>) data.getSerializableExtra("selectfollowuser");
        btn_selected.setText("已选择："+ this.selectfollowuser.size());

    }
}
